package org.dcm4che3.tool.printscp;

import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.dcm4che3.tool.common.CLIUtils;
import org.dcm4che3.tool.print.entity.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public class PrintScpMulti {
	
	private final static Logger log = LoggerFactory.getLogger(PrintSCP.class);
	private static ResourceBundle rb =
            ResourceBundle.getBundle("org.dcm4che3.tool.printscp.messages");

	public PrintScpMulti() {
	}
	
	public static void main(String[] args) throws Exception {
		CommandLine cl = parseComandLine(args);
		
        List<String> argsList = cl.getArgList();
    
        Config config = new Config();
        if (argsList.size() == 0) {
        	log.warn("no config file config. user default store path=" + config.getDicomStoreDir());
        } else {
        	config = new Config(argsList.get(0));
        	log.info("use config file={} to init program", argsList.get(0));
        }
        
        if (argsList.size() == 0) {
        	log.warn("no config file config. user default store path=" + config.getDicomStoreDir());
        } else {
        	config = new Config(argsList.get(0));
        	log.info("use config file={} to init program", argsList.get(0));
        }
        ExecutorService threadPool = Executors.newFixedThreadPool(config.getAeCustomConfig().keySet().size());
        
        JSONObject customConfig = config.getAeCustomConfig();
        for (String key : customConfig.keySet()) {
        	threadPool.execute(new PrintScpJob(key, customConfig.getJSONObject(key), config));
        }
	}
	
	static class PrintScpJob implements Runnable {
		private String key = null;
		private JSONObject aeConfig = null;
		private Config config = null;
		
		public PrintScpJob(String key, JSONObject aeConfig, Config config) {
			this.key = key;
			this.aeConfig = aeConfig;
			this.config = config;
		}
		@Override
		public void run() {
			try {
				PrintSCPV2 scpV2 = new PrintSCPV2(config, aeConfig);
				scpV2.start();
				log.info("start scp ae={} success. remoteAe=={}", key, aeConfig.getJSONObject("remote"));
			} catch (Exception e) {
				log.error("fail to start ae===={}", key, e);
			}
		}
		
	}
	
	private static CommandLine parseComandLine(String[] args)
            throws ParseException {
        Options opts = new Options();
        CLIUtils.addBindServerOption(opts);
        CLIUtils.addAEOptions(opts);
        CLIUtils.addCommonOptions(opts);
        return CLIUtils.parseComandLine(args, opts, rb, PrintScpMulti.class);
    }
}